package com.iuie.ns.system.service.code.impl;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.github.pagehelper.PageHelper;
import com.iuie.ns.frame.exception.ServiceException;
import com.iuie.ns.frame.persistence.dao.IGenericDao;
import com.iuie.ns.frame.persistence.dao.IGenericDao.MatchType;
import com.iuie.ns.frame.service.impl.BaseServiceImpl;
import com.iuie.ns.frame.utils.BeanUtils;
import com.iuie.ns.frame.utils.ListUtils;
import com.iuie.ns.frame.utils.StringUtils;
import com.iuie.ns.frame.utils.beans.UserOperateVO;
import com.iuie.ns.frame.web.dataset.vo.Page;
import com.iuie.ns.system.dao.code.ISysCodeInfoDao;
import com.iuie.ns.system.mapper.code.SysCodeInfoMapper;
import com.iuie.ns.system.service.code.ISysCodeInfoService;
import com.iuie.ns.system.tags.beans.SysDropCodeTypeVO;
import com.iuie.ns.system.vo.code.SysCodeInfoVO;
import com.iuie.ns.system.vo.code.SysCodeTypeVO;

@Service("codeInfoService")
public class SysCodeInfoServiceImpl extends BaseServiceImpl<SysCodeInfoVO> implements ISysCodeInfoService {

	@Resource
	private ISysCodeInfoDao codeInfoDao;
	
	@Resource
	private SysCodeInfoMapper codeInfoMapper;
	
	@Override
	public List<SysCodeInfoVO> findByCodeTypeId(String codeTypeId, Integer state) {
		List<SysCodeInfoVO> list = codeInfoMapper.findByCodeTypeId(codeTypeId, state);
		return list;
	}

	@Override
	public List<SysCodeInfoVO> findByCodeName(String codeName) {
		SysCodeInfoVO codeInfo = new SysCodeInfoVO();
		codeInfo.setCodeInfoName(codeName);
		Map<String, MatchType> conditions = new HashMap<String, IGenericDao.MatchType>();
		conditions.put("codeInfoName", MatchType.MATCH_LIKE);
		List<SysCodeInfoVO> list = codeInfoDao.findAll(codeInfo,conditions);
		return list;
	}

	@Override
	protected IGenericDao<SysCodeInfoVO, Serializable> getGenericDao() {
		return codeInfoDao;
	}

	@Override
	public String findMaxCodeValue(String type) {
	    return codeInfoDao.findMaxCodeValue(type);
	}

	@Override
	public List<SysDropCodeTypeVO> queryCodeInfosByTypeIdArray(Set<String> typeIds) {
		List<SysDropCodeTypeVO> list = codeInfoMapper.queryCodeInfosByTypeIdArray(typeIds);
		return list;
	}

    @Override
    public void deleteById(String id) {
        codeInfoDao.deleteById(id);
    }

    @Override
    public void saveTreeCodeInfo(UserOperateVO oper, String codeTypeId) throws Exception {
        List<SysCodeInfoVO> newRecords = BeanUtils.mapsToObjects(oper.getNewRecords(), SysCodeInfoVO.class);
        List<SysCodeInfoVO> updateRecords = BeanUtils.mapsToObjects(oper.getUpdateRecords(), SysCodeInfoVO.class);
        List<SysCodeInfoVO> deleteRecords = BeanUtils.mapsToObjects(oper.getDeleteRecords(), SysCodeInfoVO.class);
        if (ListUtils.isNotEmpty(newRecords)) {
            this.batchAdd(newRecords, codeTypeId);
        }
        if (ListUtils.isNotEmpty(updateRecords)) {
            this.batchUpdate(updateRecords);
        }
        if (ListUtils.isNotEmpty(deleteRecords)) {
            this.batchDelete(deleteRecords);
        }
    }

    @Override
    public String getNewCodeValue(String codeTypeId, Integer x) {
        String codeValue = this.findMaxCodeValue(codeTypeId);
        if (codeValue != null) {
            int intV =  Integer.parseInt(codeValue);
            String ov = String.valueOf(intV + 1 + x);
            StringBuilder sb = new StringBuilder("000000");
            for (int i = (6 - ov.length()); i < 6; i++) {
                sb.setCharAt(i, ov.charAt(i + ov.length() - 6));
            }
           return sb.toString();
        } else {
            return "000001";
        }
    }
    
    @Override
    public void editCodeInfo(SysCodeInfoVO codeInfo) {
        if (StringUtils.isEmpty(codeInfo.getCodeInfoValue())) {
            String codeTypeId = codeInfo.getCodeType().getCodeTypeId();
            String codeInfoValue = this.getNewCodeValue(codeTypeId, 0);
            codeInfo.setCodeInfoValue(codeInfoValue);
        }
        if (StringUtils.isEmpty(codeInfo.getId())) {
            codeInfo.setId(StringUtils.uuid());
            codeInfoDao.save(codeInfo);
            return ;
        }
        codeInfoDao.update(codeInfo);
    }

    @Override
    public void batchAdd(List<SysCodeInfoVO> records, String codeTypeId) {
        // 复制code info value
        Integer i = 0;
        if (ListUtils.isNotEmpty(records)) {
            Iterator<SysCodeInfoVO> it = records.iterator();
            while (it.hasNext()) {
                SysCodeInfoVO code = it.next();
                
                code.setCodeInfoValue(this.getNewCodeValue(codeTypeId, i++));
                
                SysCodeTypeVO codeType = new SysCodeTypeVO();
                codeType.setCodeTypeId(codeTypeId);
                code.setCodeType(codeType);
             }
         }
        codeInfoMapper.batchAdd(records);
    }

    @Override
    public void batchUpdate(List<SysCodeInfoVO> records) {
        codeInfoMapper.batchUpdate(records);
    }

    @Override
    public void batchDelete(List<SysCodeInfoVO> records) {
        codeInfoMapper.batchDelete(records);
    }

    @Override
    public List<SysCodeInfoVO> findCodeInfoByCodeTypeAndCondition(SysCodeInfoVO codeInfo, Page page, String typeId) {
        PageHelper.startPage(page.getPage(), page.getRows(), true);
        List<SysCodeInfoVO> list = codeInfoMapper.findCodeInfoByCodeTypeAndCondition(codeInfo, typeId);
        page.loadData(list);
        return list;
    }

    @Override
    public Integer getCodeInfoCountByTypeId(String typeId) {
        return codeInfoMapper.getCodeInfoCountByTypeId(typeId);
    }

	@Override
	public void removeCodeInfoById(String id) {
		codeInfoMapper.removeById(id);
	}

	@Override
	public void saveCodeInfo(SysCodeInfoVO codeInfo) {
		if (codeInfo == null) {
			throw new ServiceException("保存码值失败，码值信息为空！");
		}
		if (codeInfo.getCodeType() == null) {
			throw new ServiceException("保存码值失败，码值类型不能为空！");
		}
		if (StringUtils.isEmpty(codeInfo.getCodeInfoValue()) || StringUtils.isEmpty(codeInfo.getId())) {
			// 新增记录
			codeInfo.setId(StringUtils.uuid());
			if (StringUtils.isEmpty(codeInfo.getCodeInfoValue())) {
				codeInfo.setCodeInfoValue(this.getNewCodeValue(codeInfo.getCodeType().getCodeTypeId(), 0));
			}
			codeInfoDao.save(codeInfo);
		} else {
			codeInfoDao.update(codeInfo);
		}
	}

	@Override
	public SysCodeInfoVO findCodeInfoById(String id) {
		return codeInfoMapper.findCodeInfoById(id);
	}
	
}
